package com.rxyb.toolize;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * HTTP工具
 *
 * @coder duyh,@auth duyh
 * @date Nov 21, 2018
 */
@Slf4j
public class RxrcHttpUtils {

	private static final int	timeout	= 300000;

	/**
	 * POST 方式，默认超时时间5分钟
	 *
	 * @param url
	 * @param data
	 * @return
	 */
	public static String executePost(String url, String data) {
		System.out.println(url);
		return executePost(url, data, timeout);
	}

	/**
	 * GET 方式，默认超时时间5分钟
	 *
	 * @param url
	 * @return
	 */
	public static String executeGet(String url) {
		return executeGet(url, timeout);
	}

	/**
	 * POST 方式
	 *
	 * @param url
	 * @param data
	 * @param timeout
	 * @return
	 */
	public static String executePost(String url, String data, int timeout) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost method = new HttpPost(url);
		String respString = null;
		CloseableHttpResponse resp = null;
		try {
			// 设置超时时间
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
			method.setConfig(requestConfig);
			StringEntity reqEntity = new StringEntity(data, "UTF-8");
			method.setEntity(reqEntity);
			resp = httpClient.execute(method);
			int statusCode = resp.getStatusLine().getStatusCode();
			HttpEntity entity = resp.getEntity();
			if (entity != null) {
				log.info("POST数据解析");
				InputStream stream = entity.getContent();
				InputStreamReader inputStreamReader = new InputStreamReader(stream, "utf-8");
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
				String str = null;
				StringBuffer buffer = new StringBuffer();
				while ((str = bufferedReader.readLine()) != null) {
					buffer.append(str);
				}
				respString = buffer.toString();
				bufferedReader.close();
				inputStreamReader.close();
				stream.close();
				log.info("POST数据解析完毕");
			}
			// respString = EntityUtils.toString(entity, "utf-8");
			log.info("返回数据UTF-8：【{}】", respString);
			// 通讯成功
			if (HttpStatus.SC_OK == statusCode) {
				return respString;
			}
			return respString;
		} catch (Exception e) {
			log.error("发送HTTP(S)发生异常：", e);
			return null;
		} finally {
			try {
				log.info("POST链接开始关闭");
				method.releaseConnection();
				httpClient.close();
				if (resp != null) {
					resp.close();
				}
			} catch (IOException e) {
				log.error("POST链接关闭失败：", e);
			}
		}
	}

	/**
	 * POST 方式
	 *
	 * @param url
	 * @param timeout
	 * @return
	 */
	public static String executeGet(String url, int timeout) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet method = new HttpGet(url);
		String respString = null;
		CloseableHttpResponse resp = null;
		try {
			// 设置超时时间
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
			method.setConfig(requestConfig);
			resp = httpClient.execute(method);
			int statusCode = resp.getStatusLine().getStatusCode();
			HttpEntity entity = resp.getEntity();
			if (entity != null) {
				log.info("GET数据解析");
				InputStream stream = entity.getContent();
				InputStreamReader inputStreamReader = new InputStreamReader(stream, "utf-8");
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
				String str = null;
				StringBuffer buffer = new StringBuffer();
				while ((str = bufferedReader.readLine()) != null) {
					buffer.append(str);
				}
				respString = buffer.toString();
				bufferedReader.close();
				inputStreamReader.close();
				stream.close();
				log.info("GET数据解析完毕");
			}
			// respString = EntityUtils.toString(entity, "utf-8");
			log.info("GET返回数据UTF-8：【{}】", respString);
			// 通讯成功
			if (HttpStatus.SC_OK == statusCode) {
				return respString;
			}
			return respString;
		} catch (Exception e) {
			log.error("发送HTTP(S)发生异常：", e);
			return null;
		} finally {
			try {
				log.info("GET链接开始关闭");
				method.releaseConnection();
				httpClient.close();
				if (resp != null) {
					resp.close();
				}
			} catch (IOException e) {
				log.error("GET链接关闭失败：", e);
			}
		}
	}

}
